package com.dl.mall.annotation;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

import javax.annotation.Resource;

/**
 * @author DL
 * @create 2022-03-21 12:01
 */
@Component
public class TransactionalUtils {

    @Resource
    private DataSourceTransactionManager dataSourceTransactionManager;

    /**
     * 开启事务 行锁
     * @return
     */
    public TransactionStatus begin(){
        // 事务隔离级别属于mysql，事务传播行为属于spring
        TransactionStatus transaction =
                dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute());
        return transaction;
    }

    /**
     * 提交事务
     * @param transaction
     */
    public void commit(TransactionStatus transaction){
        dataSourceTransactionManager.commit(transaction);
    }

    /**
     * 回滚事务
     * @param transaction
     */
    public void rollback(TransactionStatus transaction){
        dataSourceTransactionManager.rollback(transaction);
    }
}
